<?php

namespace App\Http\Middleware;

use App\Models\UserInfo;
use Closure;
use Illuminate\Http\Request;

/**
 * 验证前台用户绑定读者证的token
 */
class CheckWebToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        //  $request->user_info = ['id'=>'1','account_id'=>'1','wechat_id'=>'1'];
        //  $request->manage_id = 1;
        //  return $next($request);

        $token = $this->getToken($request);

        if (empty($token)) {
            return  response()->json(['code' => 206, 'msg' => 'token无效']);
        }

        //验证token有效期
        $user_info = UserInfo::select('id', 'account_id', 'wechat_id', 'create_time')->where('token', $token)->first();

        if (empty($user_info)) {
            return  response()->json(['code' => 206, 'msg' => 'token无效']);
        }
        $user_info = $user_info->toArray();
        $request->user_info = $user_info;
        return $next($request);
    }

    /**
     * 获取请求参数中的 token
     * @param request  object 请求参数对象
     */
    public function getToken($request)
    {
        // $token = str_replace('Bearer ', '', $request->header('authorization'));

        // if (!$token) {
        //     $token = $request->token;
        // }

        //   $token = str_replace('Bearer ', '', $request->header('authorization'));//只能从header头获取

        $token = $request->token;
        return $token;
    }
}
